<template>
  <div>
    <el-row :gutter="20" style="margin: 10px 0;">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="card-header">
            <span style="font-size: 120%;">{{$route.meta.title}}列表</span>
            <vxe-input v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
            <el-button @click="refreshList" style="float: right; padding: 3px 0" type="text" :icon="!loading?'el-icon-refresh':'el-icon-loading'">刷新</el-button>
          </div>
          <div>
            <vxe-table resizable ref="XTable" show-overflow border height="528" stripe highlight-hover-row highlight-current-row resizable
              :loading="loading" :data="dataList" @sort-change="sortChange" :export-config="{}">
              <vxe-column field="createDate" title="创建时间" sortable></vxe-column>
              <vxe-column field="player" title="运动员" sortable></vxe-column>
              <vxe-column field="coach" title="教练员" sortable></vxe-column>
              <vxe-column field="" title="操作" width="60">
                <template #default="{ row }">
                  <el-button @click="editEvent(row)" type="primary" size="small" circle icon="el-icon-edit-outline"></el-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
              :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
            </vxe-pager>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span style="font-size: 120%;">{{$route.meta.title}}查询</span>
          </div>
          <div class="card-body">
            <el-form ref="searchForm" :model="searchForm" :rules="rules" inline-message label-width="200px">
              <el-form-item label="录入时间" prop="createDate">
                <el-date-picker v-model="searchForm.createDate" type="date" placeholder="选择日期时间" align="left" style="width: 70%;"
                   :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="测试项目" prop="templateId">
                <el-select @change="templateChange" :popper-append-to-body="false" v-model="searchForm.templateId" collapse-tags filterable placeholder="请选择" style="width: 70%;">
                  <el-option :label="item.name" :value="item.templateId" v-for="(item,index) in templateData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="usageId==3||usageId==4" label="场景">
                <el-select v-model="searchForm.scenarioId" collapse-tags filterable clearable placeholder="请选择" style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in dict_scenario" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item v-if="usageId==3||usageId==4" label="运动项目">
                <el-select @change="sportChange" v-model="searchForm.sportId" collapse-tags filterable clearable placeholder="请选择" style="width: 70%;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in sportData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="教练" prop="coachId">
                <el-select @change="coachChange" v-model="searchForm.coachId" :popper-append-to-body="false" collapse-tags filterable clearable style="width: 70%;"
                  placeholder="请选择">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in coachData" :key="index">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="运动员" prop="playerId">
                <el-button-group style="display: flex;">
                  <el-select v-model="searchForm.playerId" multiple collapse-tags filterable clearable placeholder="请选择">
                    <el-option :label="item" :value="key" v-for="(item,key,index) in playerData" :key="index">
                    </el-option>
                  </el-select>
                  <el-button @click="searchForm.playerId=Object.keys(playerData)" type="primary">全选</el-button>
                </el-button-group>
              </el-form-item>
              <el-form-item>
                <el-button type="success" size="small" icon="el-icon-s-promotion" @click="submitEnter" style="margin: 0 10px;"> 搜索</el-button>
                <vxe-button @click="tableClear" status="warning" icon="el-icon-refresh-right"> 清空</vxe-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row  style="margin: 20px 10px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="card-header">
            <span style="font-size: 120%;">在这里修改需要修改的指标值</span>
            <vxe-input v-model.trim.lazy="editFilterName" type="search" placeholder="快捷检索" @keyup="editSearchEvent"></vxe-input>
          </div>
          <div>
            <vxe-table resizable ref="XTable2" show-overflow border max-height="800" stripe highlight-hover-row highlight-current-row resizable
              :loading="editLoading" :data="editData" :export-config="{}">
              <vxe-column field="player" title="运动员" sortable></vxe-column>
              <vxe-column field="meta" title="名称" sortable></vxe-column>
              <vxe-column field="" title="数值" sortable>
                <template #default="{ row,column }">
                  <el-input v-if="!dict_character2num[row.metaId]" @change="valueChange(row)" v-model="row.valueDisplay" size="small"></el-input>
                  <vxe-select
                    v-else
                    :transfer="true"
                    size="small"
                    clearable
                    v-model="row.valueDisplay"
                    @change="valueChange(row)"
                    >
                    <vxe-option
                      v-for="(value,key,index) in dict_character2num[row.metaId]"
                      :key="index"
                      :label="key"
                      :value="value">
                    </vxe-option>
                  </vxe-select>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <div class="card-footer">
            <div style="float: left;">共有{{defaultEditData.length}}项 , 当前显示{{editData.length}}项</div>
            <el-button @click="save" type="primary" size="small" icon="iconfont icon-save"> 保存</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import {pcm4coach,currentRolePlayer,sport_by_org,coach_by_org,pcm4player,meta_cache,coach_by_sport} from '@/api/dict.js'
  import {meta_scenario,recentMetasDefault,template_allByUsageId,template_key,metasOfRecentPlayers,updateMeta} from '@/api/meta.js'
  export default {
    data() {
      return {
        a: '',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          },{
            text: '一月前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', date);
            }
          },{
            text: '半年前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', date);
            }
          },{
            text: '一年前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 30 * 12);
              picker.$emit('pick', date);
            }
          },]
        },
        usageId: this.$route.meta.usageId,
        dict_usage: this.$store.state.user.dict_usage,
        invalidateCache: false,
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        defaultDataList: [],
        dataList: [],
        loading: false,
        filterName: '',
        searchProps: [],
        dict_player: {},
        dict_sport: {},
        dict_coach: {},
        dict_meta: {},
        dict_scenario: {},
        sportData: {},
        coachData: {},
        templateData: [],
        playerData: {},
        searchForm: {
          createDate: '',
          templateId: '',
          coachId: '',
          playerId: '',
          sportId: '',
          scenarioId: '',
        },
        rules: {
          createDate: [{
            required: true,
            message: '这是必选项',
            trigger: 'change'
          }, ],
          templateId: [{
            required: true,
            message: '这是必选项',
            trigger: 'change'
          }, ],
          playerId: [{
            required: false,
            message: '这是必选项',
            trigger: 'change'
          }, ],
        },
        defaultEditData: [],
        editData: [],
        editSearchProps: [],
        editFilterName: '',
        editLoading: false,
        dict_character2num: {
            "169": {"Normal": "0", "+": "2", "++": "4", "+++": "8"},
            "170": {"-": "0", "+-": "100", "+": "250", "++": "500", "+++": "1000", "++++": "1500"},
            "171": {"-": "0.4", "+": "0.7", "++": "1.9", "+++": "5"},
            "172": {"-": "0", "+-": "5", "+": "15", "++": "40", "+++": "100"},
            "174": {"-": "0", "+-": "10", "+": "25", "++": "80", "+++": "200", "++++": "900"},
            "176": {"-": "15", "+-": "30", "+": "70", "++": "100", "+++": "300", "++++": "1000"},
            "177": {"-": "0.04", "+": "0.05"},
            "178": {"-": "0", "+-": "15", "+": "70", "++": "125", "+++": "500"},
        },
        search: false,
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.recentMetasDefault()
      })
    },

    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    methods: {
      valueChange(row) {
        row.valUpdate = true
      },
      save() {
        this.editData.forEach(item=>{
          if(item.valUpdate) {
            let data = {
              metaDataId: item.metaDataId,
              valueDisplay: item.valueDisplay,
              converterId: item.converterId
            }
            updateMeta(data).then(res=>{
              if(res.code === 200) {
                this.$message.success(item.player+'-'+item.meta+'-'+(item.valueDisplay||'空')+' --修改成功')
                item.valUpdate = false
              }
            })
          }
        })
      },
      submitEnter() {
        this.rules.playerId[0].required = true
        this.$refs.searchForm.validate((valid) => {
          if (valid) {
            let data = {
              usageId: this.usageId,
              createDate: this.$moment(this.searchForm.createDate).format('YYYY-MM-DD')+ ' 00:00:00',
              templateId: this.searchForm.templateId,
              coachId: this.searchForm.coachId,
              scenarioId: this.searchForm.scenarioId,
              sportId: this.searchForm.sportId,
              isImp: 3,
              isImportant: 3,
              playerIdStr: this.searchForm.playerId.join(',')
            }
            this.getEditData(data)
          }else{
            return false
          }
        })
      },
      editEvent(row) {
        let data = {
          usageId: row.usageId,
          createDate: row.createDate+ ' 00:00:00',
          templateId: row.templateId,
          coachId: row.coachId,
          scenarioId: row.scenarioId,
          sportId: row.sportId,
          isImp: 3,
          isImportant: 3,
          playerIdStr: row.playerIds
        }
        this.getEditData(data)
      },
      getEditData(data) {
        this.editLoading = true
        metasOfRecentPlayers(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length!=0){
              res.data.forEach(item=>{
                item.meta = this.dict_meta[item.metaId]
                item.player = this.dict_player[item.playerId]
              })
              this.editSearchProps = Object.keys(res.data[0])
              this.defaultEditData = res.data
              this.editData = res.data
              this.editLoading = false
            }else{
              this.defaultEditData = []
              this.editData = []
              this.editLoading = false
            }
          }else{
            this.defaultEditData = []
            this.editData = []
            this.editLoading = false
            this.$message.error(res.message)
          }
        })
      },
      editSearchEvent() {
        const filterName = this.$XEUtils.toValueString(this.editFilterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.editSearchProps
          const rest = this.defaultEditData.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.editData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.editData = this.defaultEditData
        }
      },
      tableClear() {
        this.searchForm.templateId = ''
        this.searchForm.createDate = ''
        this.searchForm.playerId = ''
      },
      sportChange(val) {
        this.coachData = {}
        this.searchForm.coachId = ''
        this.playerData = {}
        this.searchForm.playerId = ''
        coach_by_sport({sportId: val || this.searchForm.sportId}).then(res=>{
          this.coachData = res
        })
      },
      templateChange(val) {
        if(this.usageId == 1 || this.usageId == 2) {
          template_key({templateId:val || this.searchForm.templateId}).then(res=>{
            this.searchForm.sportId = res.data.sportId
          })
          this.coachData = {}
          this.searchForm.coachId = ''
          this.playerData = {}
          this.searchForm.playerId = ''
          pcm4coach({sportId: this.searchForm.sportId}).then(res=>{
            this.coachData = res
          })
        }
      },
      coachChange(val) {
        this.playerData = {}
        this.searchForm.playerId = ''
        pcm4player({coachId: this.searchForm.coachId||val}).then(res=>{
          this.playerData = res
        })
      },
      refreshList() {
        this.invalidateCache = true
        this.recentMetasDefault()
      },
      recentMetasDefault() {
        let data = {
          usageId: this.usageId,
          invalidateCache: this.invalidateCache
        }
        recentMetasDefault(data).then(res=>{
          if(res.code === 200) {
              if(res.data.length != 0) {
                this.init_list_data(res.data)
              }else{
                this.defaultDataList = []
              }
            }else{
              this.defaultDataList = []
              this.$message.error(res.message)
            }
          }).then(()=>{
            this.findList()
          })
      },
      init_list_data(data) {
        data.forEach(item=>{
          if(item.playerIds){
            let arr = item.playerIds.split(',')
            let playerArr = []
            arr.forEach(player=>{
              playerArr.push(this.dict_player[player])
            })
            item.player = playerArr.join(',')
          }
          item.coach = this.dict_coach[item.coachId]
        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          sport_by_org().then(res=>{
            this.dict_sport = res
            this.sportData = res
          })
          coach_by_org().then(res=>{
            this.dict_coach = res
            this.coachData = res
            this.searchForm.coachId = Object.keys(res)[0]
            this.coachChange()
          })
          template_allByUsageId({usageId:this.usageId}).then(res=>{
            this.templateData = res.data
          })
          meta_cache().then(res=>{
            this.dict_meta = res
          })
          meta_scenario().then(res=>{
            res.data.forEach(item=>{
              this.dict_scenario[item.scenarioId] = item.name
            })
          })
          currentRolePlayer().then(res=>{
            this.dict_player = res
            resolve()
          })
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
          }
          this.search = true
        } else {
          this.dataList = this.defaultDataList
     }
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if(this.insertSuccess){
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult/this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length-1])
            this.insertSuccess = false
          }else{
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>
  .card-header{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .card-body{
    height: 590px;
  }
  .card-footer{
    width: 100%;
    text-align: center;
    margin-top: 20px;
  }
</style>
